<template>
<view>
<u-cell-group>
  <block v-for="(item, index) in localForms" :key="index">
    <!-- <van-field v-if="helper.isInputItem(item.type)" :key="index" :data-index="index" :label="item.key" :value="item.value" :required="item.required" :placeholder="item.placeholder" @change="onChange" :border="false"></van-field> -->
    <u-cell v-if="helper.isInputItem(item.type)" size="large" :label="item.key">
      <!-- <view slot="value">1111</view> -->
      <u-input slot="value" fontSize="14" @change="onChange" @focus="onFocus(index)" :value="item.value" :required="item.required" :border="false"  :placeholder="item.placeholder"></u-input>
    </u-cell>
    <!-- <u-cell v-if="helper.isDateItem(item.type)" @click="onDateItemClick" :data-item="item" :data-index="index" :title="item.key" :required="item.required" is-link :value="item.time?item.time:item.placeholder" :border="false"></u-cell> -->
    <u-cell v-else-if="helper.isDateItem(item.type)" @click="onDateItemClick" :name="{item,index}" :title="item.key" :required="item.required" is-link :value="item.time?item.time:item.placeholder" :border="false"></u-cell>
    <u-cell v-else  @click="handleTakePhoto" :name="index" :title="item.key" :required="item.required" is-link :value="item.value?'已上传':item.placeholder" :border="false"></u-cell>
  </block>
</u-cell-group>
<!-- <u-popup :show="datePopVisible" mode="bottom" :customStyle="{height:'40%'}" @close="onClose"> -->
  <!-- <van-datetime-picker :mode="currentFrom.type||'date'" :value="currentValue" @input="onDateInput" @cancel="onClose" @confirm="onDateConfirm"></van-datetime-picker> -->
  <u-datetime-picker :show="datePopVisible" :mode="currentFrom.type||'date'" v-model="currentValue" @cancel="onClose" @confirm="onDateConfirm"></u-datetime-picker>
<!-- </u-popup> -->
</view>
</template>
<script module="helper" lang="wxs" src="@/wxs/customForm.wxs"></script>
<script lang='ts'>
import { Component, Vue,Prop,Watch} from 'vue-property-decorator'
import { IFromItem } from "./form.schema";
import DateUtil from "@/mixins/date";
import { uploadFile } from "@/utils/upload";
@Component
export default class CustomForm extends Vue {
    @Prop()
    forms:Array<any>
    localForms= [] as IFromItem[]
    datePopVisible:boolean=false
    currentValue:number
    currentFrom={} as IFromItem
    currentIndex:any=null

    /** 日期选择配置 */
    minHour:number=10
    maxHour:number= 20
    minDate:number=new Date().getTime()
    maxDate:number=new Date(2019, 10, 1).getTime()
    isFirstEnter:boolean=false
    created(){
        this.formsChange(this.$props.forms)
    }
    @Watch("forms")
    formsChange(newValue){
        if (!this.isFirstEnter) {
            this.transformFormToData(newValue);
            this.setData({ isFirstEnter: true });
        }
    }
   transformFormToData(forms: IFromItem[]) {
    const localForms = forms.map(item => {
      item.value = "";
      return item;
    });
    this.setData({ localForms });
  }

  onDateItemClick({
    name:{
      item,
      index
    }
  }) {
    this.setData({
      currentFrom: item,
      currentIndex: index,
      currentValue:
        item.value || item.type === "time" ? "12:00" : new Date().getTime(),
    });
    this.setDatePopVisible(true);
  }
  onFocus(e){
    this.currentIndex=e
  }
    /** 表单变化 */
  onChange(e) {
    this.localForms[this.currentIndex].value = e;
  }
    onClose() {
    this.setDatePopVisible(false);
  }

  setDatePopVisible(datePopVisible) {
    this.setData({ datePopVisible });
  }
  onDateConfirm(e) {
    let time = "";
    const dateUtil = new DateUtil(e.value);
    switch (this.currentFrom.type) {
      case "date":
        time = dateUtil.getYMDs();
        break;
      case "time":
        time = e.value;
        break;
      case "datetime":
        time = dateUtil.getYMDHMSs();
    }
    this.setData({
      [`localForms[${this.currentIndex}].value`]: this.currentValue,
      [`localForms[${this.currentIndex}].time`]: time,
    });
    this.setDatePopVisible(false);
  }
    /** 拍照 */
  handleTakePhoto(e) {
    const index=e.name
    uni
      .chooseImage({
        count: 1,
        sizeType: ["original", "compressed"],
        sourceType: ["album", "camera"],
        success:({ tempFilePaths: [url] })=>{
            uploadFile(url)
          .then(res => {
            this.localForms[index].value = res
          })
          .catch(err => {
            this.$Popup.toast("上传失败");
          });
        }
      })
  }
    /** date表单变化 */
  onDateInput({ detail: currentValue }) {
    this.setData({ currentValue });
  }

  verificationField(form: IFromItem) {
    switch (form.type) {
      case "id":
        return this.$global.isIDnumber(form.value);
      case "phone":
        return this.$global.isPhone(form.value);
      case "number":
        return this.$global.isNumber(+form.value);
      default:
        return true;
    }
  }
    /** 验证表单 */
  verificationForm() {
    const emptyItem = this.localForms
      .filter(item => item.required)
      .find(item => !item.value);

    if (emptyItem) {
      this.$Popup.toast(`${emptyItem.key}不可为空`);
      return false;
    }

    const errorItem = this.localForms.find(
      item => !!item.value && !this.verificationField(item),
    );

    if (errorItem) {
      this.$Popup.toast(`请填写正确的${errorItem.key}`);
      return false;
    }

    return true;
  }
}   
</script>
<style scoped>
</style>